package com.szyt.basicframe.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.szyt.basicframe.util.IdUtil;
import com.szyt.basicframe.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("添加数据时，公共字段自动填充");
        Long currentUserId = SecurityUtils.getCurrentUserId();
        LocalDateTime now = LocalDateTime.now();
        if (getFieldValByName("id", metaObject) == null) {
            metaObject.setValue("id", IdUtil.getId());
        }
        if (getFieldValByName("createTime", metaObject) == null) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
        }
        if (getFieldValByName("createBy", metaObject) == null) {
            this.strictInsertFill(metaObject, "createBy", Long.class, currentUserId);
        }
        if (getFieldValByName("updateTime", metaObject) == null) {
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, now);
        }
        if (getFieldValByName("updateBy", metaObject) == null) {
            this.strictInsertFill(metaObject, "updateBy", Long.class, currentUserId);
        }
        if (getFieldValByName("delFlag", metaObject) == null) {
            this.strictInsertFill(metaObject, "delFlag", Boolean.class, Boolean.FALSE);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("更新数据时，公共字段自动填充");
        log.info("自动填充前数据："+metaObject.toString());
        Long currentUserId = SecurityUtils.getCurrentUserId();
        LocalDateTime now = LocalDateTime.now();
        if (getFieldValByName("updateTime", metaObject) == null) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, now);
        }
        if (getFieldValByName("updateBy", metaObject) == null) {
            this.strictUpdateFill(metaObject, "updateBy", Long.class, currentUserId);
        }
        log.info("自动填充后数据："+metaObject.toString());
    }
}
